<template>
	<view>
		<sunui-upbasic :upImgConfig="upImgBasic" @onUpImg="upBasicData" @onImgDel="delImgInfo" ref="uImage"></sunui-upbasic>
		<!-- <button type="primary" @tap="getUpImgInfoBasic">获取上传Basic图片信息</button>
		<button type="primary" @tap="uImageTap">手动上传图片</button>

		<button type="primary" @click="on">清楚缓存</button>
		<button type="primary" @click="addrpid(8)">set</button>
		<button type="primary" @tap="zipImag">压缩上传图片</button> -->
		<!-- <image :src="item" v-for="(item,index) in imgList" :key="index"></image> -->
		<!-- <image :src="item" v-for="(item,index) in imgList" :key="index"></image> -->
		<image :src="src"></image>
		<!-- <view v-for="(item,index) in imgList" :key="index">
			{{item}}
		</view> -->
		<!-- <w-compress ref='wCompress' /> -->
		
		<!-- <uploadImg></uploadImg> -->
		
		<!-- 
		{{this.$store.getters.getRepairId}}
		{{this.$store.getters.getEquipmentInfo.id}} -->

		<!-- 	{{this.$store.getters.getEquipmentInfo.engineer_id}} -->
	</view>
</template>

<script>
	import sunuiUpbasic from './sunui-upbasic.vue'
	import uploadImg from '../components/zipUploadImg.vue'
	import {
		getEngineerserById
	} from '@/api/user/index.js'
	import config from '@/utils/config.js'
	import WCompress from '@/components/w-compress/w-compress.vue'
	import toBlob from './zip.js';
	import {
		getInfoSync,
		setInfoSync,
		getRpIdSync,
		setRpIdSync,
		removeInfoSync,
		removeRpId
	} from '@/utils/store.js'
	export default {

		components: {
			sunuiUpbasic,
			WCompress,
			uploadImg
		},
		data() {
			return {
				imgList: [],

				src: localStorage.getItem("test"),
				list: [],
				basicArr: [],
				// 基础版配置
				upImgBasic: {
					// 后端图片接口地址
					basicConfig: {
						url: config.BaseUrl + '/repair_user?action=UploadFile'
					},
					// 是否开启提示(提醒上传图片的数量)
					// tips: false,
					// 是否开启notli(开启的话就是选择完直接上传，关闭的话当count满足数量时才上传)
					notli: true,
					// 图片数量
					count: 2,
					// 相机来源(相机->camera,相册->album,两者都有->all,默认all)
					sourceType: 'camera',
					// 是否压缩上传照片(仅小程序生效)
					sizeType: true,
					// 上传图片背景修改 
					upBgColor: '#ededed',
					// 上传icon图标颜色修改(仅限于iconfont)
					upIconColor: '#666666',
					// 上传svg图标名称
					// upSvgIconName: 'icon-card',
					// 上传文字描述(仅限四个字)
					upTextDesc: '上传图片',
					// 删除按钮位置(left,right,bleft,bright),默认右上角
					delBtnLocation: '',
					// 是否隐藏添加图片
					// isAddImage: false,
					// 是否隐藏删除图标
					// isDelIcon: false,
					// 删除图标定义背景颜色
					// delIconColor: '',
					// 删除图标字体颜色
					// delIconText: '',
					// 上传图标替换(+),是个http,https图片地址(https://www.playsort.cn/right.png)
					iconReplace: ''
				}
			};
		},
		onLoad() {

		},
		methods: {
			on() {

				removeRpId()
				removeInfoSync()
			},
			addrpid(e) {
				this.$store.dispatch('setRpId', e)
			},

			// 手动上传图片(适用于表单等上传) -2019/05/10增加
			uImageTap() {
				this.$refs.uImage.uploadimage(this.upImgBasic);
			},
			// 删除图片 -2019/05/12(本地图片进行删除)
			async delImgInfo(e) {
				console.log('你删除的图片地址为:', e, this.basicArr.splice(e.index, 1));
			},
			// 基础版
			async upBasicData(e) {
				console.log('===>', e);
				// 上传图片数组
				let arrImg = [];
				for (let i = 0, len = e.length; i < len; i++) {
					try {
						if (e[i].path_server != "") {
							await arrImg.push(e[i].path_server.split(','));
						}
					} catch (err) {
						console.log('上传失败...');
					}
				}
				// 图片信息保存到data数组
				this.basicArr = arrImg;
				// 可以根据长度来判断图片是否上传成功. 2019/4/11新增
				if (arrImg.length == this.upImgBasic.count) {
					uni.showToast({
						title: `上传成功`,
						icon: 'none'
					});
				}
			},
			// 获取上传图片basic
			getUpImgInfoBasic() {
				console.log('后端转成一维数组:', this.basicArr.join().split(','));
			},

			//压缩上传
		    zipImag() {
				let _this = this
				uni.chooseImage({
					count: 9, //默认9
					sizeType: ['compressed'], //可以指定是原图还是压缩图，默认二者都有
					sourceType: ['all'],
					success: (res) => {
						uni.showLoading({
							title: '图片压缩中...'
						});
					   _this.zip(res.tempFilePaths)
					}
				});
			},
			 toBlos(res){
				const _this = this
				res.forEach((item,index) => {
					let base64 = item.split(',')[1]
					toBlob.base64ToBlob({
						b64data: base64,
						contentType: 'image/png'
					}).then(res => {
						// // 转后后的blob对象
						// _this.faceOnly(res.path)
					  	// _this.imgList[index] =  res.path
						
						 _this.up_img(res.path).then(res =>{
							
							 JSON.parse(res)
							 console.log(res)
						 })
					})
				})
				uni.showToast({
					title: `上传成功`,
					icon: 'none'
				});
			},
			/**
			 * 批量上传
			 * @param {Object} res base64
			 */
			async uploads(res) {
				let arr = []
				for(let index in res){
					 arr[index]= await this.up_img(this.imgList[index])	
				}
				console.log(arr)
				uni.showToast({
					title: `上传成功`,
					icon: 'success'
				});
				this.imgList = res
				return arr;
			},
			/**
			 * 压缩
			 * @param {Object} tempFilePaths
			 */
			async zip(tempFilePaths) {
				this.$refs.wCompress.start(tempFilePaths, {
						pixels: 200000, // 最大分辨率，默认二百万
						quality: 0.1, // 压缩质量，默认0.8
						type: 'png', // 图片类型，默认jpg
						base64: true, // 是否返回base64，默认false，非H5有效
					})
					.then(res => {
						uni.hideLoading()
						// this.imgList =res
						console.log(res)
						uni.showLoading({
							title: '图片上传中...'
						});
						this.uploads(res)
					})
					.catch(e => {
						console.log(e)
						uni.hideLoading()
					})
			},
			/**上传
			 * @param {Object} url
			 */
		   async up_img(url) {
				return new Promise((resolve, reject) => {
					uni.uploadFile({
						url: config.BaseUrl + '/repair_user?action=UploadFile', //仅为示例，非真实的接口地址
						filePath: url,
						name: 'file[]',
						formData: {},
						success: (uploadFileRes) => {
							resolve(JSON.parse(uploadFileRes.data).result[0].file);
						}
					});
				})
			},
			/* faceOnly(file) {
				uni.uploadFile({
					url: config.BaseUrl + '/repair_user?action=UploadFile', //仅为示例，非真实的接口地址
					filePath: file,
					name: 'file[]',
					formData: {
						'user': 'test'
					},
					success: (uploadFileRes) => {
						let url = JSON.parse(uploadFileRes.data).result[0].file
						this.src = url
						console.log(url)
					}
				});
			} */
		}
	}
	
	//网上提供的旋转function
	const rotateImg = (img, direction, canvas, times = 1) => {
		console.log('开始旋转')
		//最小与最大旋转方向，图片旋转4次后回到原方向    
		var min_step = 0;
		var max_step = 3;
		if (img == null) return;
	
		//img的高度和宽度不能在img元素隐藏后获取，否则会出错    
		var height = img.height;
		var width = img.width;
		let maxWidth = 500;
		let canvasWidth = width; //图片原始长宽  
		let canvasHeight = height;
		let base = canvasWidth / canvasHeight;
		console.log(maxWidth);
		if (canvasWidth > maxWidth) {
			canvasWidth = maxWidth;
			canvasHeight = Math.floor(canvasWidth / base);
		}
		width = canvasWidth;
		height = canvasHeight;
		var step = 0;
	
		if (step == null) {
			step = min_step;
		}
	
		if (direction == 'right') {
			step += times;
			//旋转到原位置，即超过最大值    
			step > max_step && (step = min_step);
		} else if (direction == 'left') {
			step -= times;
			step < min_step && (step = max_step);
		} else { //不旋转  
			step = 0;
		}
	
		//旋转角度以弧度值为参数    
		var degree = step * 90 * Math.PI / 180;
		var ctx = canvas.getContext('2d');
		console.log(degree)
		console.log(step)
		switch (step) {
			case 1:
				console.log('右旋转 90度')
				canvas.width = height;
				canvas.height = width;
				ctx.rotate(degree);
				ctx.drawImage(img, 0, -height, width, height);
				break;
			case 2:
				//console.log('旋转 180度')  
				canvas.width = width;
				canvas.height = height;
				ctx.rotate(degree);
				ctx.drawImage(img, -width, -height, width, height);
				break;
			case 3:
				console.log('左旋转 90度')
				canvas.width = height;
				canvas.height = width;
				ctx.rotate(degree);
				ctx.drawImage(img, -width, 0, width, height);
				break;
			default: //不旋转  
				canvas.width = width;
				canvas.height = height;
				ctx.drawImage(img, 0, 0, width, height);
				break;
		}
	
		let baseStr = canvas.toDataURL("image/jpeg", 1);
		return baseStr;
	}
	
	const comprossImage = async (imgSrc, maxWidth, func) => {  
	    if(!imgSrc) return 0;  
	    return new Promise((resolve, reject) => {  
	        uni.getImageInfo({  
	            src: imgSrc,  
	            success(res) {  
	                let img = new Image();  
	                img.src = res.path;  
	                console.log(img)  
	
	                let canvas = document.createElement('canvas');  
	
	                let obj = new Object();  
	                obj.img = img;  
	                obj.canvas = canvas;  
	                resolve(func(obj));  
	            }  
	        });  
	    })  
	}  
	
	
	
	/**  
	 * @desc 获取图片信息，使用exif.js库，具体用法请在github中搜索  
	 * @param {Object} file 上传的图片文件  
	 * @param {String} tag 需要获取的信息 例如：'Orientation'旋转信息  
	 * @return {Promise<Any>} 读取是个异步操作，返回指定的图片信息  
	 */  
	const getImageTag = (file, tag, suc) => {  
	    if (!file) return 0;  
	    return new Promise((resolve, reject) => {  
	        /* eslint-disable func-names */  
	        // 箭头函数会修改this，所以这里不能用箭头函数  
	        let imgObj = new Image()  
	        imgObj.src = file  
	        console.log(imgObj)  
	        uni.getImageInfo({  
	            src: file,  
	            success(res) {  
	                Exif.getData(imgObj, function () {  
	                    Exif.getAllTags(this);    
	                    let or = Exif.getTag(this,'Orientation');//这个Orientation 就是我们判断需不需要旋转的值了，有1、3、6、8  
	                    resolve(suc(or))  
	                });  
	            }  
	        })  
	    });  
	};  
	
	
</script>

<style lang="scss" scoped>
	/deep/ .lb-picker {
		.lb-picker-column-label {
			color: #f0ad4e;
		}

		.lb-picker-column-active {
			.lb-picker-column-label {
				color: #007aff;
				font-weight: 700;
			}
		}
	}
</style>
